﻿using Authentication.Model.Interface;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Identifier;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.ServiceCommand
{
    public class RetrieveUsersServiceCommand : ProviderServiceCommand<IUserProvider, RetrieveUsersRequest, RetrieveUsersResponse>
    {
        public RetrieveUsersServiceCommand(IUserProvider providers) : base(providers) { }

        protected override void Validate(RetrieveUsersRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
        }

        protected override bool OnExecute(RetrieveUsersResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            List<UserRecord> records = null;
            var applicationKey = Request.Header.ApplicationKey;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
            var objects = Providers.RetrieveUsers(out totalRecord, Request.Header.ApplicationKey, Request.GroupIdentifier, Request.Name, Request.IsActive, pageSize, pageIndex);
            if (objects != null)
            {
                records = objects.Select(x => new UserRecord
                {
                    ApplicationKey = x.GuidKey,
                    UserName = x.UserName,
                    Email = x.AccountInfo == null ? string.Empty : (x.AccountInfo.Email ?? string.Empty),
                    FirstName = x.AccountInfo == null ? string.Empty : (x.AccountInfo.FirstName ?? string.Empty),
                    LastName = x.AccountInfo == null ? string.Empty : (x.AccountInfo.LastName ?? string.Empty),
                    Mobile = x.AccountInfo == null ? string.Empty : (x.AccountInfo.MobilePin ?? string.Empty),
                    Active = x.IsActive,
                    GroupIdentifier = x.GroupId
                }).ToList();
            }

            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };
            return isSuccess;
        }
    }
}
